<template>
  <div class="DinamicForm">
    <el-form ref="ruleForm" :model="formData" label-position="right" status-icon>
      <template v-for="(key, i) in formLayoutKeys" :key="keyRow(i)">
        <el-row :gutter="10" style="height: 40px;">
          <el-col
            :style="{ width: item.width }"
            :sm="12"
            :md="item.span"
            :lg="item.span"
            :xl="item.span"
            v-for="(item, j) in formLayout[key]"
            :key="keyRowCol(i, j)"
            :class="[
              {
                'el-col-right': item.isRowRight
              }
            ]"
          >
            <!-- <template v-if="item.type">
              
            </template> -->
            <DinamicFormItem
                :formItemConfig="item"
                v-model="formData[item.propName]"
                @notify="handleFormWidgetNotify"
              >
              <template #[name]="scope" v-for="name in slots">
                  <slot :name="name" :scope="{ ...scope,ruleForm }"></slot>
              </template>
            </DinamicFormItem>
          </el-col>
        </el-row>
      </template>

      <!-- <el-row :gutter="10" style="height: 40px">
        <template
          v-for="(config, index) in dialogFormInformation.filterFormConfigs"
          :key="index + 'config'"
        >
          <el-col
            :sm="config.col"
            :md="config.col"
            :lg="config.col"
            :xl="config.col"
          >
            <DinamicFormItem :config="config" :form="form"></DinamicFormItem>
          </el-col>
        </template>
        <el-col style="flex: 1 1 auto">
          <slot name="button"></slot>
        </el-col>
      </el-row> -->
    </el-form>
  </div>
</template>

<script setup>
import {
  reactive,
  ref,
  defineExpose,
  onMounted,
  watch,
  computed,
  useSlots
} from "vue";
import DinamicFormItem from "./DinamicFormItem.vue";
import { generateFieldDefaultValue } from "./handleDynamicFormLogic.js";

const emits = defineEmits(["submit","notify","update:modelValue"]);

const dialogVisible = ref(false);
const drawerTitle = ref("");
// const form = ref({});
const ruleForm = ref();
const props = defineProps(["formConfigs","modelValue"]);
const formLayout = computed(()=>generateFormLayout(props.formConfigs));
const formData = computed({
  get(){
    props.formConfigs.forEach(x=>{
      if(x.type && !props.modelValue[x.propName]){
        props.modelValue[x.propName]=generateFieldDefaultValue(x)
      }
    })
    return new Proxy(props.modelValue,{
      set(target, key, newValue){
        target[key]=newValue
        emits('update:modelValue',target)
        return true;
      }
    })
  },
  set(val){
    emits('update:modelValue',val)
  }
})
// watch(()=>formData.value,(newValue,oldValue)=>{
// debugger
//   emits('update:modelValue',{...newValue})
// },{deep:true})

const formSlots = useSlots()
const slots = computed(() => {
    // 过滤出属于 form 组件的插槽
    let solts = Object.keys(formSlots);
    return solts
});

function handleFormWidgetNotify(params) {
  emits("notify", params);
}
/*
 * 表单布局的key,主要是row信息,用于生成row、col
 */
const formLayoutKeys = computed(() => {
  let keys = Object.keys(formLayout.value);
  return keys.sort();
});

const show = (title, isVisible) => {
  dialogVisible.value = isVisible;
  drawerTitle.value = title;
};

// 根据传入的配置，生成表单的布局配置
function generateFormLayout(formItems) {
  let formLayout = {};
  let row = [];
  let index = 0;
  let newFormItems = formItems.filter((x) => !x.isHidden);
  for (let i = 0; i < newFormItems.length; i++) {
    if (newFormItems[i].span > 24 || newFormItems[i].span < 0) {
      throw new Error(`formItems中第${i}个item的colSpan超出最长限制24`);
    }
    if (!newFormItems[i].span && !newFormItems[i].width) {
      newFormItems[i].span = 12; //不设置span或者width，默认span=12
    }
    if (!newFormItems[i].span && newFormItems[i].width) {
      newFormItems[i].span = 0;
    }
    row.push(newFormItems[i]);
    // 是否单独占一行
    if (newFormItems[i].isSingleRow) {
      formLayout[`row-${index}`] = [...row];
      row = [];
      index++;
    } else {
      let rowColSpan = 0;
      row.forEach((item) => {
        rowColSpan += item.span;
      });
      if (rowColSpan == 24) {
        formLayout[`row-${index}`] = [...row];
        row = [];
        index++;
      } else if (rowColSpan > 24) {
        let lastItem = row.pop();
        formLayout[`row-${index}`] = [...row];
        index++;
        row = [lastItem];
      }
      // 对最后一行的处理
      if (row.length && i === newFormItems.length - 1) {
        formLayout[`row-${index}`] = [...row];
        row = [];
        index++;
      }
    }
  }
  return formLayout;
}
// row的key
function keyRow(i) {
  return "row_" + i;
}
// col的key
function keyRowCol(i, j) {
  return "row_" + i + "_col_" + j;
}
// 动态表单item的key,兼容propName、prop、key
function keyOfFormItem(item) {
  return item.propName || item.prop || item.key;
}

defineExpose({ show,ruleForm });
</script>

<style lang="less" scoped>
.DinamicForm {
  .dinamic-drawer__content {
    height: 100%;
    .el-form {
      //   height:100%;
    }
    .dinamic-drawer__footer {
      height: 40px;
      display: flex;
      justify-content: flex-end;
      padding-right: 5%;
    }
  }
}
</style>
<style lang="less">
.DinamicForm {
  .el-drawer__body {
    padding: 0px 0px 20px 0px;
  }
}
</style>
